package com.lancoo.znbkxx.teacher.utils;

import android.content.Context;
import android.content.res.Configuration;
import android.util.Base64;
import android.util.Log;
import android.widget.Chronometer;
import android.widget.Toast;

import java.io.File;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LancooUtils {

    //首字母大写
    public static String captureString(String name) {
        char[] cs = name.toCharArray();
        cs[0] -= 32;
        return String.valueOf(cs);
    }

    /**
     * Ascii转换为字符串
     *
     * @param value
     * @return
     */
    public static String asciiToString(String value) {
        StringBuffer sbu = new StringBuffer();
        String[] chars = value.split(",");
        for (int i = 0; i < chars.length; i++) {
            sbu.append((char) Integer.parseInt(chars[i]));
        }
        return sbu.toString();
    }

    /**
     * 字符串转换为Ascii
     *
     * @param value
     * @return
     */
    public static String stringToAscii(String value) {
        StringBuffer sbu = new StringBuffer();
        char[] chars = value.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (i != chars.length - 1) {
                sbu.append((int) chars[i]).append(",");
            } else {
                sbu.append((int) chars[i]);
            }
        }
        return sbu.toString();

    }

    /**
     * 数字转汉字【新】
     *
     * @param num
     * @return
     */
    private static String nums[] = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
    private static String pos_units[] = {"", "十", "百", "千"};
    private static String weight_units[] = {"", "万", "亿"};

    public static String numberToChinese(int num) {
        if (num == 0) {
            return "零";
        }

        int weigth = 0;//节权位
        String chinese = "";
        String chinese_section = "";
        boolean setZero = false;//下一小节是否需要零，第一次没有上一小节所以为false
        while (num > 0) {
            int section = num % 10000;//得到最后面的小节
            if (setZero) {//判断上一小节的千位是否为零，是就设置零
                chinese = nums[0] + chinese;
            }
            chinese_section = sectionTrans(section);
            if (section != 0) {//判断是都加节权位
                chinese_section = chinese_section + weight_units[weigth];
            }
            chinese = chinese_section + chinese;
            chinese_section = "";
            Log.d("TAG", chinese_section);

            setZero = (section < 1000) && (section > 0);
            num = num / 10000;
            weigth++;
        }
        if ((chinese.length() == 2 || (chinese.length() == 3)) && chinese.contains("一十")) {
            chinese = chinese.substring(1, chinese.length());
        }
        if (chinese.indexOf("一十") == 0) {
            chinese = chinese.replaceFirst("一十", "十");
        }

        return chinese;
    }

    /**
     * 将每段数字转汉子
     *
     * @param section
     * @return
     */
    public static String sectionTrans(int section) {
        StringBuilder section_chinese = new StringBuilder();
        int pos = 0;//小节内部权位的计数器
        boolean zero = true;//小节内部的置零判断，每一个小节只能有一个零。
        while (section > 0) {
            int v = section % 10;//得到最后一个数
            if (v == 0) {
                if (!zero) {
                    zero = true;//需要补零的操作，确保对连续多个零只是输出一个
                    section_chinese.insert(0, nums[0]);
                }
            } else {
                zero = false;//有非零数字就把置零打开
                section_chinese.insert(0, pos_units[pos]);
                section_chinese.insert(0, nums[v]);
            }
            pos++;
            section = section / 10;
        }

        return section_chinese.toString();
    }


    //    String numbers = "1|2|3|4|5";
////    使用split拆分
//    String[] numberArray = numbers.split("\\| ");
    /*
     * @Title 输出一个字符串数组
     * @param AllString 需要拆解的字符窜
     * @param thisString 需要判断的字符
     * @param i_begin 分隔符所占的字符数
     * */
    public static String[] returnArray(String allString, String thisString, int i_begin) {
        int count = 0;
        int i_strArrayflag = getStringFrequency(allString, thisString);
        String[] strArray = new String[i_strArrayflag + 1];
        String strA = allString;

        while (strA.indexOf(thisString) != -1) {
            count++;
            strArray[count - 1] = strA.substring(0, strA.indexOf(thisString));
            //将字符串出现c的位置之前的全部截取掉
            strA = strA.substring(strA.indexOf(thisString) + i_begin);
        }
        strArray[count] = strA;
        printArray(strArray);
        return strArray;
    }

    /*
     *@Title//判断某个字符在整个字符串中出现的次数、频率
     *@param allString：整个字符串
     *@param thisString：需要判断的字符
     * */
    public static int getStringFrequency(String allString, String thisString) {

        int count = 0;
        String str = allString;//你要测试的字符串
        str = str.toLowerCase();//将字符串全部转化成小写//考虑大小写：
        //index为字符串中第一次出现c的位置，如果字符串中没有c将返回-1
        int index = str.indexOf(thisString);
        //如果字符串中有c
        while (str.indexOf(thisString) != -1) {
            count++;
            str = str.substring(str.indexOf(thisString) + 1);
        }
        return count;
    }

    //输出数组
    public static void printArray(String[] array) {
        for (int i = 0; i < array.length; i++) {
            System.out.print("" + i + "====yyyyy==" + array[i]);
            if (i == array.length - 1) {
                System.out.print("\n");
            } else {
                System.out.print(",");
            }
        }
    }


    /**
     * 秒转化为天小时分秒字符串
     *
     * @param seconds
     * @return String
     */

    public static String formatSeconds(long seconds) {

        String timeStr = seconds + "秒";

        if (seconds > 60) {

            long second = seconds % 60;

            long min = seconds / 60;

            timeStr = min + "分" + second + "秒";

            if (min > 60) {

                min = (seconds / 60) % 60;

                long hour = (seconds / 60) / 60;

                timeStr = hour + "小时" + min + "分" + second + "秒";

                if (hour > 24) {

                    hour = ((seconds / 60) / 60) % 24;

                    long day = (((seconds / 60) / 60) / 24);

                    timeStr = day + "天" + hour + "小时" + min + "分" + second + "秒";

                }

            }

        }

        return timeStr;

    }


    public static String getDays(long second) {//计算秒有多少小时
        long days = 00;
        if (second > 3600 * 24) {
            days = second / (3600 * 24);
        }
        return days + "";
    }

    public static String getHours(long second) {//计算秒有多少小时
        long h = 00;
        long temp = second % (3600 * 24);
        if (second > 3600 * 24) {
            if (temp != 0) {
                h = temp / 3600;
            }
        } else {
            h = second / 3600;
        }
        return h + "";
    }

    public static String getMins(long second) {//计算秒有多少分
        long m = 00;
        long temp = second % 3600;
        if (second > 3600) {
            if (temp != 0) {
                if (temp > 60) {
                    m = temp / 60;
                }
            }
        } else {
            m = second / 60;
        }
        return m + "";
    }

    public static String getSeconds(long second) {//计算秒有多少秒
        long s = 0;
        long temp = second % 3600;
        if (second > 3600) {
            if (temp != 0) {
                if (temp > 60) {
                    if (temp % 60 != 0) {
                        s = temp % 60;
                    }
                } else {
                    s = temp;
                }
            }
        } else {
            if (second % 60 != 0) {
                s = second % 60;
            }
        }
        return s + "";
    }


    public static String getBase64StuID(String stuId) {
        String encodedString = Base64.encodeToString(stuId.getBytes(), Base64.DEFAULT).trim();
        String stuID_1 = encodedString.substring(0, 1);
        String stuID_2 = encodedString.substring(1, 2);
        String stuID_3 = encodedString.substring(2);
        return stuID_2 + stuID_1 + stuID_3;
    }

    // 例如：输入0.52----52%            输入0.1235----12.4%(注意：这个有四舍五入)
    public static String getPercentInstance(double d) {
        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMaximumFractionDigits(2);//这个1的意识是保存结果到小数点后几位，但是特别声明：这个结果已经先＊100了。
        Log.e("getPercentInstance", "========自动四舍五入==============" + nf.format(d));//自动四舍五入。
        return nf.format(d);
    }

//    public  static float getCorrectRate(int small,int big){
//        float size = (float)small/big;
//        DecimalFormat df = new DecimalFormat("0.00");//格式化小数，不足的补0
//        return  Float.valueOf(df.format(size));
//    }

    public static double getCorrectRate(double small, double big) {
        double size = small / big;
        DecimalFormat df = new DecimalFormat("0.00");//格式化小数，不足的补0
        return Double.valueOf(df.format(size));
    }

    /*
     * 对double数据 进行去除没用的.0
     * */
    public static String killlingDouble(double value) {
        int b = (int) value;
        if (value == b) {
            return String.valueOf(b);
        } else {
            return String.valueOf(value);
        }
    }

    /**
     * 对double数据进行取精度.
     * * 	 * @param value	 *
     * double数据.
     * * @param scale	 *
     * 精度位数(保留的小数位数).
     * * @param roundingMode	 *
     * 精度取值方式.
     * * @return 精度计算后的数据.
     */
    public static double round(double value, int scale, int roundingMode) {
        BigDecimal bd = new BigDecimal(value);
        bd = bd.setScale(scale, roundingMode);
        double d = bd.doubleValue();
        bd = null;
        return d;
    }

    /*
     * 计时器换算
     * */
    public static String getChronometerSeconds(Chronometer cmt) {
        /**
         *
         * @param cmt  Chronometer控件
         * @return 小时+分钟+秒数  的所有秒数
         */
        int totalss = 0;
        String string = cmt.getText().toString();
        if (string.length() == 7) {

            String[] split = string.split(":");
            String string2 = split[0];
            int hour = Integer.parseInt(string2);
            int Hours = hour * 3600;
            String string3 = split[1];
            int min = Integer.parseInt(string3);
            int Mins = min * 60;
            int SS = Integer.parseInt(split[2]);
            totalss = Hours + Mins + SS;
            return String.valueOf(totalss);
        } else if (string.length() == 5) {

            String[] split = string.split(":");
            String string3 = split[0];
            int min = Integer.parseInt(string3);
            int Mins = min * 60;
            int SS = Integer.parseInt(split[1]);

            totalss = Mins + SS;
            return String.valueOf(totalss);
        }
        return String.valueOf(totalss);


    }

    //删除文件夹和文件夹里面的文件
    public static void deleteDir(final String pPath) {
        File dir = new File(pPath);
        deleteDirWihtFile(dir);
    }

    public static void deleteDirWihtFile(File dir) {
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;
        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete(); // 删除所有文件
            else if (file.isDirectory())
                deleteDirWihtFile(file); // 递规的方式删除文件夹
        }
        dir.delete();// 删除目录本身
    }

    //判断文件是否存在

    public static boolean fileIsExists(String strFile) {
        try {
            File f = new File(strFile);
            if (!f.exists()) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }


//    //获取当前时间戳
//    long timeStamp = System.currentTimeMillis();
//    String time = stampToDate(timeStamp);
//    Log.d("xxxxx", time);
//
//    //获取当前时间
//    Calendar c = Calendar.getInstance();//可以对每个时间域单独修改
//    int year = c.get(Calendar.YEAR);
//    int month = c.get(Calendar.MONTH);
//    int date = c.get(Calendar.DATE);
//    int hour = c.get(Calendar.HOUR_OF_DAY);
//    int minute = c.get(Calendar.MINUTE);
//    int second = c.get(Calendar.SECOND);
//    Log.d("xxxxx",year + "/" + (month+1) + "/" + date + " " +hour + ":" +minute + ":" + second);

    /*
     * 将时间转换为时间戳
     */
    public static String dateToStamp(String time) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(time);
        long ts = date.getTime();
        return String.valueOf(ts);
    }

    /*
     * 将时间戳转换为时间
     */
    public static String stampToDate(long timeMillis) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(timeMillis);
        return simpleDateFormat.format(date);
    }


    public static String getTime() {
        long time = System.currentTimeMillis() / 1000;//获取系统时间的10位的时间戳
        String str = String.valueOf(time);
        return str;
    }


    public static String[] concat(String[] a, String[] b) {
        String[] c = new String[a.length + b.length];
        System.arraycopy(a, 0, c, 0, a.length);
        System.arraycopy(b, 0, c, a.length, b.length);
        return c;
    }


    public static void Long_i(String tag, String msg) {  //信息太长,分段打印
        //因为String的length是字符数量不是字节数量所以为了防止中文字符过多，
        //  把4*1024的MAX字节打印长度改为2001字符数
        int max_str_length = 2001 - tag.length();
        //大于4000时
        while (msg.length() > max_str_length) {
            Log.i(tag, msg.substring(0, max_str_length));
            msg = msg.substring(max_str_length);
        }
        //剩余部分
        Log.i(tag, msg);
    }

    /*
     * 判断是手机还是平板
     * true：平板
     * false：手机
     * */
    public static boolean isTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    /***
     * replaceAll,忽略大小写
     *
     * @param input
     * @param regex
     * @param replacement
     * @return
     */
    public static String replaceAll(String input, String regex, String replacement) {
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(input);
        String result = m.replaceAll(replacement);
        return result;
    }
}
